// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/common/exception/exception.h>

namespace kumo::pollux::dwio::common {
    // Base class for closeable object which need to be explicitly closed before
    // being destructed
    class Closeable {
    public:
        Closeable() : closed_{false} {
        }

        virtual ~Closeable() {
            destroy();
        }

        bool isClosed() const {
            return closed_;
        }

        void close() {
            if (!closed_) {
                closed_ = true;
                doClose();
            }
        }

    protected:
        void markClosed() {
            closed_ = true;
        }

        virtual void doClose() {
        }

        void destroy() {
            if (!closed_) {
                DWIO_WARN_EVERY_N(1000, "close() not called");
                try {
                    close();
                } catch (...) {
                    DWIO_WARN("failed to call close()");
                }
            }
            DWIO_ENSURE(closed_);
        }

    private:
        bool closed_;
    };
} // namespace kumo::pollux::dwio::common
